package com.moshme.web.controller.project;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.moshme.common.annotation.Log;
import com.moshme.common.constant.FeiJuProject;
import com.moshme.common.core.controller.BaseController;
import com.moshme.common.core.domain.AjaxResult;
import com.moshme.common.core.domain.entity.SysUser;
import com.moshme.common.enums.BusinessType;
import com.moshme.common.utils.StringUtils;
import com.moshme.project.domain.ProjectInfo;
import com.moshme.project.domain.ProjectStep;
import com.moshme.project.domain.ProjectStepUser;
import com.moshme.project.service.ProjectStepService;
import com.moshme.project.service.ProjectStepUserService;
import com.moshme.project.service.ProjectInfoService;
import com.moshme.project.service.StageSurveyService;
import com.moshme.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * @author 望夜
 * @date 2023/8/22---16:50
 * @SuppressWarnings({"all"})
 */
@RestController
@RequestMapping("/project/step")
@Api("阶段通用")
public class ProjectStepController extends BaseController {
    @Autowired
    private ProjectStepService projectStepService;
    @Autowired(required = false)
    private ProjectStepUserService projectStepUserService;
    @Autowired
    private ProjectInfoService projectInfoService;
    @Autowired(required = false)
    private StageSurveyService stageSurveyService;
    @Autowired
    private ISysUserService sysUserService;

    @Log(title = "获取阶段信息", businessType = BusinessType.INSERT)
    @GetMapping(value = {"/", "/{stepId}"})
    @ApiOperation(value = "获取阶段信息")
    public AjaxResult getInfo(@PathVariable(value = "stepId", required = false) Long stepId) {
        AjaxResult ajax = AjaxResult.success();

        if (StringUtils.isNotNull(stepId)) {
            ProjectStep projectStep = projectStepService.getById(stepId);
            ajax.put(AjaxResult.DATA_TAG, projectStep);
        }

        return ajax;
    }

    //TODO 项目阶段鉴权可以菜单-自定义按钮权限字符；   再到角色中分配
//    @PreAuthorize("@ss.hasPermi('project:step:insert')")
    @Log(title = "阶段预设", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "提交阶段预设")
    @Transactional
    public AjaxResult submit(@RequestBody @Validated ProjectStep projectStep) {
        projectStep.setSubmitTime(LocalDateTime.now());
        projectStep.setSubmitBy(getUsername());

        try {
            Long projectId = projectStep.getProjectId();
            Integer clickStep = projectStep.getClickStep();

            ProjectInfo projectInfo = projectInfoService.getById(projectId);

            LambdaQueryWrapper<ProjectStep> wrapper = new LambdaQueryWrapper<ProjectStep>().eq(ProjectStep::getProjectId, projectId).eq(ProjectStep::getProjectStep, clickStep);
            ProjectStep isHave = projectStepService.getOne(wrapper);

            LocalDate[] dateArray = projectStep.getDateArray();
            if (dateArray != null && dateArray.length >= 2) {
                projectStep.setStepStartDate(dateArray[0]);
                projectStep.setStepEndDate(dateArray[1]);

                if (projectStep.getStepStartDate().compareTo(projectInfo.getProjectStartDate()) < 0) {
                    return error("当前阶段开始时间不应早于项目开始时间");
                }
                if (projectStep.getStepEndDate().compareTo(projectInfo.getProjectEndDate()) > 0) {
                    return error("当前阶段结束时间不应超过项目结束时间");
                }

                projectStep.setImplDays((int) ChronoUnit.DAYS.between(dateArray[0], dateArray[1]));
            }
            projectStep.setProjectStep(clickStep);

            //创建勘察阶段
            if (projectStep.getProjectStep() == FeiJuProject.KC.getValue() && (projectStep.getStepStatus() == null || projectStep.getStepStatus() == 0)) {
                    stageSurveyService.add(projectId);
            }

            if(projectStep.getStepStatus() == null || projectStep.getStepStatus() == 0){
                projectStep.setStepStatus(1);
            }
            Long[] stepUserIds = projectStep.getStepUserIds();
            if(stepUserIds != null && stepUserIds.length > 0 && Arrays.asList(stepUserIds).contains(projectStep.getStepLeader())){
                SysUser sysUser = sysUserService.selectUserById(projectStep.getStepLeader());
                return error("负责人【"+ sysUser.getNickName()+ "】不应该在组员中");
            }
            if (StringUtils.isNotNull(isHave)) {
                projectStepService.updateById(projectStep);
                //删除 新建关联
                projectStepUserService.deleteProjectStepUser(projectStep.getStepId());
                insertProjectStepUser(projectStep);
            } else {
                projectStep.setStepId(null);
                projectStepService.save(projectStep);
                //关联
                insertProjectStepUser(projectStep);
            }

        } catch (Exception e) {
            return error("阶段提交失败——" + e.getMessage());
        }

        return success();
    }

//    @PreAuthorize("@ss.hasPermi('project:info:edit')")
    @Log(title = "阶段完结", businessType = BusinessType.UPDATE)
    @PutMapping("/{projectId}/{clickStep}")
    @ApiOperation(value = "阶段完结")
    @Transactional
    public AjaxResult stageOver(@PathVariable(value = "projectId", required = false) Long projectId,
                                @PathVariable(value = "clickStep", required = false) Integer clickStep) {
        //当前项目阶段预设完才能进行项目完结
        LambdaQueryWrapper<ProjectStep> eq = new LambdaQueryWrapper<ProjectStep>().eq(ProjectStep::getProjectId, projectId).eq(ProjectStep::getProjectStep, clickStep);
        ProjectStep projectStep = projectStepService.getOne(eq);
        if (projectStep == null) {
            return error("请先进行阶段预设!");
        }
        if(projectStep.getStepStatus() == 2){
            return error("该阶段已经完结了");
        }

        projectStep.setStepStatus(2);

        //TODO 项目状态以后再说
//        if (projectInfo.getProjectStep() > FeiJuProject.HTQD.getValue()) {
//            projectInfo.setProjectStep(FeiJuProject.YWXM.getValue());
//        }
//        projectInfoService.updateById(projectInfo);

        projectStepService.updateById(projectStep);

        return success();
    }

    private void insertProjectStepUser(ProjectStep projectStep) {
        Long[] stepUserIds = projectStep.getStepUserIds();
        Long stepId = projectStep.getStepId();
        ArrayList<ProjectStepUser> list = new ArrayList<>();
        for (Long stepUserId : stepUserIds) {
            ProjectStepUser projectStepUser = new ProjectStepUser();
            projectStepUser.setStepId(stepId);
            projectStepUser.setUserId(stepUserId);
            list.add(projectStepUser);
        }

        projectStepUserService.saveBatch(list);
    }

}
